import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;

/**
 * Created by YYL on 2017/6/18.
 */
public class WordCount {
    //嵌套类 Mapper
    //Mapper<keyin,valuein,keyout,valueout>
    public static class WordCountMapper extends
            Mapper<Object, Text, Text, IntWritable> {

        //one赋值为1
        public static final IntWritable one = new IntWritable(1);
        private Text word = new Text();

        public void map(Object key, Text value, Context context)
                throws IOException, InterruptedException {
            // Java语言中，提供了专门用来分析字符串的类StringTokenizer（位于java.util包中）。
            // 该类可以将字符串分解为独立使用的单词，并称之为语言符号。
            // 语言符号之间由定界符（delim）或者是空格、制表符、换行符等典型的空白字符来分隔。
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                this.word.set(itr.nextToken());
                //context.write(word, one)，即将分割后的字符串形成键值对，<单词，1>
                context.write(this.word, one);
            }
        }

    }

    //嵌套类Reducer
    //Reduce<keyin,valuein,keyout,valueout>
    //Reducer的valuein类型要和Mapper的va lueout类型一致,
    // Reducer的valuein是Mapper的valueout经过shuffle之后的值
    public static class WordCountReducer  extends
            Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();//0

        public void reduce(Text key, Iterable<IntWritable> values, Context context)
                throws IOException, InterruptedException {
            int sum = 0;
            IntWritable val;
            for (Iterator i = values.iterator(); i.hasNext(); sum += val.get()) {
                val = (IntWritable) i.next();
            }
            this.result.set(sum);
            context.write(key, this.result);
        }
    }

    public static void main(String[] args)
            throws IOException, ClassNotFoundException, InterruptedException {
        FileUtil.deleteDir("output");
        //获得Configuration配置 Configuration: core-default.xml, core-site.xml
        Configuration conf = new Configuration();
        //本地运行
        String[] otherArgs = new String[]{"input/dream.txt","output"};
        //发布到集群上
        // String[] otherArgs = new String[]{"hdfs://hdp-node-01:9000/WordCountDir/","hdfs://hdp-node-01:9000/WordCountDir/out"};
        if (otherArgs.length != 2) {
            System.err.println("Usage:Merge and duplicate removal <in> <out>");
            System.exit(2);
        }
        //设置Job属性
        Job job = Job.getInstance(conf, "WordCount");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(WordCount.WordCountMapper.class);
        job.setReducerClass(WordCount.WordCountReducer .class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

//        配置输入和输出路径
        //传入input path
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        //传入output path，输出路径应该为空，否则报错org.apache.hadoop.mapred.FileAlreadyExistsException。
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        //是否正常退出
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}